package com.dingup.homework.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingup.api.Util.RedisUtils;
import com.dingup.api.base.HttpResContent;
import com.dingup.homework.bean.DO.HwHomeworkDO;
import com.dingup.homework.bean.DO.HwHomeworkRecordDO;
import com.dingup.homework.bean.DTO.HomeworkProgressDTO;
import com.dingup.homework.bean.DTO.HomeworkRecordDODataMapInfo;
import com.dingup.homework.bean.HomeworkAnswerItem;
import com.dingup.homework.dao.HwHomeworkRecordsMapper;
import com.dingup.homework.enums.HomeworkRecordStatusEnum;
import com.dingup.homework.enums.HomeworkStatusEnum;
import com.dingup.homework.enums.QuestionTypeEnum;
import com.dingup.homework.feign.client.user.ClassFeignClient;
import com.dingup.homework.service.*;
import com.suyeer.basic.util.BDateUtil;
import com.suyeer.basic.util.BHttpResUtil;
import com.suyeer.basic.util.BJsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static com.dingup.api.base.BaseUtil.*;
import static com.dingup.homework.util.ConstUtil.*;

/**
 * 学生获取作业
 *
 * @author jun 2018/11/8.
 */
@Controller
@RequestMapping("/homework")
public class HomeworkController {

    @Autowired
    private HwHomeworkService hwHomeworkService;

    @Autowired
    private HwHomeworkRecordsService hwHomeworkRecordsService;

    @Autowired
    private HwHomeworkRecordsMapper hwHomeworkRecordsMapper;

    @Autowired
    private HwSsatWordRecordService hwSsatWordRecordService;

    @Autowired
    private TeacherCorrectService teacherCorrectService;

    @Autowired
    private ClassFeignClient classFeignClient;

    @Autowired
    private SendMsgService sendMsgService;

    @RequestMapping(value = "/list_homework.do", method = RequestMethod.POST)
    public void listHomework(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<HashMap<String, List<HomeworkRecordDODataMapInfo>>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取学生作业列表");
        try {
            String userId = RedisUtils.getInstance().getUserId(request);
            List<HomeworkRecordDODataMapInfo> retList = hwHomeworkRecordsService.listByStudentId(userId);
            HashMap<String, List<HomeworkRecordDODataMapInfo>> retMap = new HashMap<>();
            retMap.put("normalHomeworkList", new ArrayList<>());
            retMap.put("historyHomeworkList", new ArrayList<>());
            retMap.put("expiredHomeworkList", new ArrayList<>());
            retMap.put("willExpiredHomeworkList", new ArrayList<>());
            for (HomeworkRecordDODataMapInfo h : retList) {
                h.setExpiredDateStr(BDateUtil.getShortDateStr(h.getExpiredTime()));
                h.setIfTodayExpired(false);
                if (h.getStatus() != HomeworkRecordStatusEnum.WAITING) {
                    retMap.get("historyHomeworkList").add(h);
                } else if (h.getBeExpired()) {
                    retMap.get("expiredHomeworkList").add(h);
                } else if (BDateUtil.calcDay(h.getExpiredTime()) < 2) {
                    h.setIfTodayExpired(true);
                    retMap.get("willExpiredHomeworkList").add(h);
                } else {
                    retMap.get("normalHomeworkList").add(h);
                }
            }
            // response.
            saveSuccessMsgAndData(hrc, retMap);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/get_homework.do", method = RequestMethod.POST)
    public void getHomework(@RequestParam(PARAM_HOMEWORK_ID) Integer homeworkId,
                            HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<HwHomeworkDO> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取某次作业内容");
        try {
            // check.
            checkParam(PARAM_HOMEWORK_ID, homeworkId);
            // do.
            HwHomeworkDO hwHomework = hwHomeworkService.getById(homeworkId);
            // response.
            saveSuccessMsgAndData(hrc, hwHomework);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/get_homework_record.do", method = RequestMethod.POST)
    public void getHomeworkRecord(@RequestParam(PARAM_HOMEWORK_RECORD_ID) Integer homeworkRecordId,
                                  HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<JSONObject> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取学生作业记录");
        try {
            // check.
            checkParam(PARAM_HOMEWORK_ID, homeworkRecordId);
            // do.
            HomeworkRecordDODataMapInfo hwHomeworkRecord = hwHomeworkRecordsService.getById(homeworkRecordId);
            if (hwHomeworkRecord == null) {
                throw new Exception("获取作业记录失败!");
            }
            HwHomeworkDO hwHomework = hwHomeworkService.getById(hwHomeworkRecord.getHomeworkId());
            if (hwHomework == null) {
                throw new Exception("获取作业失败!");
            }
            JSONObject retObj = BJsonUtil.changeType(hwHomework, JSONObject.class);
            retObj.put("homeworkId", hwHomeworkRecord.getHomeworkId());
            retObj.put("homeworkRecordId", hwHomeworkRecord.getId());
            retObj.put("homeworkRecordStatus", hwHomeworkRecord.getStatus());
            retObj.put("progress", hwHomeworkRecord.getProgress());
            retObj.put("totalQuestion", hwHomeworkRecord.getTotalQuestion());
            retObj.put("studentName", hwHomeworkRecord.getStudentName());
            retObj.put("studentId", hwHomeworkRecord.getStudentId());
            retObj.put("correctionDocUrl", hwHomeworkRecord.getCorrectionDocUrl());
            JSONArray qArr = retObj.getJSONArray("questionList");
            List<HomeworkAnswerItem> answerItemList = hwHomeworkRecord.getAnswerData();
            if (answerItemList != null) {
                for (int i = 0; i < answerItemList.size(); i++) {
                    JSONObject qItem = qArr.getJSONObject(i);
                    qItem.put("answerData", answerItemList.get(i));
                }
            }
            // response.
            saveSuccessMsgAndData(hrc, retObj);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/save_subjective_answer.do", method = RequestMethod.POST)
    public void saveSubjectAnswer(@RequestParam(PARAM_HOMEWORK_RECORD_ID) Integer homeworkRecordId,
                                  @RequestParam(PARAM_DOC_URL) String docUrl,
                                  @RequestParam(PARAM_AUDIO_URL) String audioUrl,
                                  HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("保存主观题答案");
        try {
            // check.
            checkParam(PARAM_HOMEWORK_ID, homeworkRecordId);
            // do.
            HwHomeworkRecordDO hwHomeworkRecord = hwHomeworkRecordsService.getById(homeworkRecordId);
            List<HomeworkAnswerItem> homeworkAnswerItemList = hwHomeworkRecord.getAnswerData();
            if (homeworkAnswerItemList == null) {
                homeworkAnswerItemList = new ArrayList<>();
            }
            HomeworkAnswerItem homeworkAnswerItem = new HomeworkAnswerItem(docUrl, audioUrl);
            homeworkAnswerItemList.add(homeworkAnswerItem);
            hwHomeworkRecord.setAnswerData(homeworkAnswerItemList);
            hwHomeworkRecord.setAnswerTime(new Date());
            hwHomeworkRecord.setProgress(1);
            hwHomeworkRecord.setStatus(HomeworkRecordStatusEnum.FINISHED);
            hwHomeworkRecordsService.update(hwHomeworkRecord);
            // response.
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/list_progress.do", method = RequestMethod.POST)
    public void getProgress(@RequestParam(PARAM_HOMEWORK_ID) Integer homeworkId,
                            HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<HomeworkProgressDTO>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取作业进度");
        try {
            // check.
            checkParam(PARAM_HOMEWORK_ID, homeworkId);
            // do.
            List<HomeworkProgressDTO> retList = hwHomeworkRecordsService.listProgress(homeworkId);
            // response.
            saveSuccessMsgAndData(hrc, retList);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/finish_homework.do", method = RequestMethod.POST)
    public void finishHomework(@RequestParam(PARAM_HOMEWORK_RECORD_ID) Integer homeworkRecordId,
                               HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("完成作业");
        try {
            // check.
            checkParam(PARAM_HOMEWORK_RECORD_ID, homeworkRecordId);
            // do.
            String userId = RedisUtils.getInstance().getUserId(request);
            HwHomeworkRecordDO hwHomeworkRecord = hwHomeworkRecordsService.getById(homeworkRecordId);
            if (homeworkRecordId == null) {
                throw new Exception("作业记录不存在!");
            }
            List<HomeworkAnswerItem> answerItemList = hwHomeworkRecord.getAnswerData();
            HomeworkRecordStatusEnum homeworkRecordStatus = HomeworkRecordStatusEnum.CORRECTED;
            if (answerItemList != null) {
                for (HomeworkAnswerItem h : answerItemList) {
                    QuestionTypeEnum questionType = h.getQuestionType();
                    if (questionType == QuestionTypeEnum.ALL || questionType == QuestionTypeEnum.SUBJECTIVE ||
                            questionType == QuestionTypeEnum.SPEAKING || questionType == QuestionTypeEnum.WRITING) {
                        homeworkRecordStatus = HomeworkRecordStatusEnum.FINISHED;
                    }
                }
            }
            if (hwHomeworkRecord.getStudentId().equals(userId)) {
                hwHomeworkRecord.setStatus(homeworkRecordStatus);
                hwHomeworkRecord.setAnswerTime(new Date());
                if (!hwHomeworkRecordsService.update(hwHomeworkRecord)) {
                    throw new Exception("修改作业记录失败!");
                }
            }

            sendMsgService.sendHomeworkFinishMsgForTeacher(hwHomeworkRecord.getId(), hwHomeworkRecord.getHomeworkId());
            //修改老师批改记录的状态
            teacherCorrectService.updateWhenStudentFinish(hwHomeworkRecord.getId(), null, null, null, HomeworkStatusEnum.UNCORRECTED);
            // response.
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/add_homework_get_class.do", method = RequestMethod.POST)
    public void addHomeworkGetClass(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<Map<String, Object>>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("添加作业获取班级");
        try {
            String userId = RedisUtils.getInstance().getUserId(request);
            List<Map<String, Object>> res = classFeignClient.getClassInfoForAddHomework(userId);
            // response.
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/add_homework_get_user.do", method = RequestMethod.POST)
    public void addHomeworkGetUser(HttpServletRequest request, HttpServletResponse response,
                                   Integer classId) {
        HttpResContent<Map<String, Object>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("添加作业获取老师和学生");
        try {
            Map<String, Object> users = classFeignClient.getStudentAndTeacherForAddHomework(classId);
            // response.
            saveSuccessMsgAndData(hrc, users);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }
}
